package com.kmxd.ams.app.event.efile.command;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.kmxd.ams.client.event.efile.AttachmentConvertEvent;
import com.kmxd.ams.client.oss.IEfileRecordSvc;
import com.kmxd.ams.client.oss.IOssAttachmentSvc;
import com.kmxd.ams.client.oss.dto.OssAttachmentQueryDTO;
import com.kmxd.ams.client.oss.vo.OssAttachmentListVO;
import com.kmxd.ams.client.system.ISysConfigSvc;
import com.kmxd.ams.core.common.constant.ConfigConst;
import com.kmxd.ams.core.common.enums.TransferStatusEnum;
import com.kmxd.ams.core.convert.DocConvertUtil;
import com.kmxd.ams.core.convert.impl.PdfService;
import com.kmxd.ams.core.oss.template.OssTemplate;
import com.kmxd.ams.core.util.ConfigUtil;
import com.kmxd.ams.infra.oss.entity.OssAttachment;
import com.kmxd.ams.infra.system.mapper.SysFondsMapper;
import java.util.Date;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 电子文件转换
 *
 * @author ZuoLG
 */
@Slf4j
@Component
@AllArgsConstructor
public class AttachmentConvertCmd {
  private final SysFondsMapper sysFondsMapper;
  private IEfileRecordSvc efileSvc;
  private IOssAttachmentSvc ossAttachmentSvc;
  private OssTemplate ossTemplate;
  private ISysConfigSvc sysConfigSvc;
  private DocConvertUtil convertUtil;

  /** 电子文件转换 */
  @Transactional(rollbackFor = Exception.class)
  public void efileConvert(AttachmentConvertEvent event) throws Exception {
    log.debug("docIds: {} ", event.getReq().toString());
    fileOpt(event);
  }

  /**
   * 电子文件操作
   *
   * @param event
   */
  private void fileOpt(AttachmentConvertEvent event) {
    // 获取转换的文件类型
    String fileTypeConf = sysConfigSvc.getConfigContentByKey(ConfigConst.OSS_FILE_TYPE);
    // 获取转换方式
    String transferConf = sysConfigSvc.getConfigContentByKey(ConfigConst.OSS_TRANSFER);
    // 转换后缀
    String transferExt = ConfigUtil.getVal(transferConf, ConfigConst.TRANSFER_EXT);
    // 转换方式
    String transferType = ConfigUtil.getVal(transferConf, ConfigConst.TRANSFER_TYPE);
    // 转换Url
    String transferURL = ConfigUtil.getVal(transferConf, ConfigConst.TRANSFER_URL);
    // 设置支持的格式
    if (ObjectUtil.isNotNull(fileTypeConf)) {
      List<String> words = ConfigUtil.getStrs(fileTypeConf, "word");
      List<String> excels = ConfigUtil.getStrs(fileTypeConf, "excel");
      List<String> ppts = ConfigUtil.getStrs(fileTypeConf, "ppt");
      List<String> pdfs = ConfigUtil.getStrs(fileTypeConf, "pdf");
      List<String> imgs = ConfigUtil.getStrs(fileTypeConf, "img");
      List<String> htmls = ConfigUtil.getStrs(fileTypeConf, "html");
      List<String> tiffs = ConfigUtil.getStrs(fileTypeConf, "tiff");
      convertUtil.init(transferType).setFileType(words, PdfService.TYPE_WORD);
      convertUtil.init(transferType).setFileType(excels, PdfService.TYPE_EXCEL);
      convertUtil.init(transferType).setFileType(ppts, PdfService.TYPE_PPT);
      convertUtil.init(transferType).setFileType(pdfs, PdfService.TYPE_PDF);
      convertUtil.init(transferType).setFileType(imgs, PdfService.TYPE_IMG);
      convertUtil.init(transferType).setFileType(htmls, PdfService.TYPE_HTML);
      convertUtil.init(transferType).setFileType(tiffs, PdfService.TYPE_TIFF);
    }
    OssAttachmentQueryDTO queryDTO = new OssAttachmentQueryDTO();
    // "装换状态：1待处理，2转换中，3成功，4失败，99不支持转换，0不需要转换"
    queryDTO.setTransferStatus(1L);
    List<OssAttachmentListVO> efiles = ossAttachmentSvc.selectListByDay(queryDTO);
    List<OssAttachment> efileUpdate = Lists.newArrayList();
    efiles.forEach(
        efile -> {
          try {
            //此处存在问题
            String basePath = ossTemplate.getAttachmentPath(efile.getDefPath());
            String srcPath = ossTemplate.getAttachmentPath(efile.getDefPath()) + efile.getPath();
            // 判断文件是否存在 "装换状态：1待处理，2转换中，3成功，4失败，99不支持转换，0不需要转换"
            efile.setTransferStatus(
                FileUtil.exist(srcPath)
                    ? TransferStatusEnum.S2.getCode()
                    : TransferStatusEnum.S4.getCode());

            String pdfPath =
                    efile.getPath().substring(0, efile.getPath().lastIndexOf('.')) + "." + transferExt;
            efile.setTransferPath(pdfPath);
            // 根据类型转换执行不同的转换,转换方式：aspose|shuke|youhong
            // 执行文件转换
            convertUtil.init(transferType).docConvert(srcPath, basePath + pdfPath);
            efile.setTransferStatus(TransferStatusEnum.S3.getCode());
          } catch (Exception e) {
            log.error(e.getMessage(), e);
            efile.setTransferStatus(TransferStatusEnum.S4.getCode());
            efile.setUpdateTime(new Date());
          }
          OssAttachment record = BeanUtil.copyProperties(efile, OssAttachment.class);
          efileUpdate.add(record);
        });
    if (!efileUpdate.isEmpty()) {
      ossAttachmentSvc.updateBatchById(efileUpdate);
    }
  }
}
